package com.huahua.api.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huahua.api.entity.base.BaseWebsocketRequest;
import com.huahua.api.entity.dto.mofang.LoginDto;
import com.huahua.api.entity.dto.mofang.LoginWebSocketParam;
import com.huahua.api.entity.pojo.mofang.MofangLogin;
import com.huahua.api.service.MofangLoginService;
import com.huahua.api.util.MoFangUtil;
import com.huahua.api.util.WebSocketUtil;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

@ServerEndpoint(path = "/ws/{arg}", host = "${ws.host}", port = "${ws.port}")
public class MyWebSocket {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    MofangLoginService mofangLoginService;


    @BeforeHandshake
    public void handshake(Session session, HttpHeaders headers, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap) {
        session.setSubprotocols("stomp");
    }

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap) {
        System.out.println("new connection");
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("one connection closed");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("收到：" + message);
        try {
            BaseWebsocketRequest simpleWebsocketRequest = objectMapper.readValue(message, BaseWebsocketRequest.class);
            if ("mofang".equals(simpleWebsocketRequest.getSystem())) {
                //魔方
                if ("getLoginUrl".equals(simpleWebsocketRequest.getCommand())) {
                    //登录
                    TypeReference<BaseWebsocketRequest<LoginWebSocketParam>> valueTypeRef = new TypeReference<BaseWebsocketRequest<LoginWebSocketParam>>() {
                    };
                    BaseWebsocketRequest<LoginWebSocketParam> param = objectMapper.readValue(message, valueTypeRef);
                    LoginDto loginDto = MoFangUtil.getLoginUrl();
                    WebSocketUtil.sendMessage(session, simpleWebsocketRequest, loginDto.getLoginUrl());
                    MofangLogin entity = new MofangLogin();
                    entity.setCookies(loginDto.getCookie());
                    entity.setStatus(1);
                    entity.setLoginUrl(loginDto.getLoginUrl());
                    entity.setCount(0);
                    entity.setLastUpdateTime(LocalDateTime.now());
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setEmail(param.getParam().getEmail());
                    mofangLoginService.save(entity);
                }
            }
        } catch (JsonProcessingException e) {
            session.sendText("格式转化异常");
            e.printStackTrace();
        }
    }

    @OnBinary
    public void onBinary(Session session, byte[] bytes) {
        for (byte b : bytes) {
            System.out.println(b);
        }
        session.sendBinary(bytes);
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    System.out.println("read idle");
                    break;
                case WRITER_IDLE:
                    System.out.println("write idle");
                    break;
                case ALL_IDLE:
                    System.out.println("all idle");
                    break;
                default:
                    break;
            }
        }
    }

}